<template>
  <view class="content">
    <view class="hunt" :style="wxHuntStyle">
      <hederBox>
        <template #center>
          <uni-easyinput
            styleOther="width: 83vw; margin-top: 10rpx;margin-right: 30rpx;"
            class="uni-mt-5"
            suffixIcon="search"
            v-model="searchName"
            placeholder="请输入关键字进行查询"
            @iconClick="iconClick(searchName)"
          />
        </template>
      </hederBox>
    </view>
    <view class="search-box" v-show="show">
      <view class="search-item">
        <text class="header-title min">搜索历史</text>
        <view class="white-box">
          <uni-tag
            v-for="item in historyData"
            :key="item.filedName"
            type="white"
            @click="tagClick"
            :text="item.filedName"
            inverted="false"
            customStyle="margin: 10rpx !important;display: inline-block;"
          />
        </view>
      </view>
      <view class="search-item">
        <text class="header-title min">热门搜索</text>
        <view class="white-box">
          <!-- {{ HotData }} -->
          <uni-tag
            v-for="item in HotData"
            :key="item"
            type="white"
            @click="hotTagClick"
            :text="item"
            inverted="false"
            customStyle="margin: 10rpx !important;display: inline-block;"
          />
        </view>
      </view>
    </view>
    <view class="tabulation-box" v-if="!show">
      <div class="tabulation-type">
        <uni-data-checklist
          styleOther="padding: 30rpx 4vw; width: 81vw;"
          :wrap="true"
          :value="changeName"
          :localdata="localdata"
          @change="changeChecklist"
        />
      </div>

      <view style="padding: 4vw; background: #ffffff">
        <view
          v-if="
            changeVal == '企业' || changeVal == '人才' || changeVal == '集体'
          "
        >
          <none-data v-if="enterpriseList.length === 0" />
          <view
            v-else
            class="card-container"
            v-for="item in enterpriseList"
            :key="item.id"
          >
            <enterprise-item-card
              v-if="changeVal == '企业'"
              :card-detail="item"
              @handle-enterprise-name-click="goEnterpriseDetail"
              @honour-portrayal-click="goPortrayalPage"
            />

            <!-- @honour-total-click="goEnterpriseDetail"
              @honour-portrayal-click="goPortrayalPage" -->
            <!-- @enterprise-name-click="" -->
            <personalCard :information="item" v-if="changeVal == '人才'">
              <template #btn>
                <view class="btn-box-geren">
                  <button class="btn" @tap="personalDetails(item)">
                    个人空间
                  </button>
                  <!-- <button class="btn">加为好友</button> -->
                </view>
              </template>
            </personalCard>
          </view>
          
          
          <view v-if="changeVal == '商城'">
            <commodity :list="listData" />
          </view>
        </view>
      </view>
    </view>
    <u-popup
      :show="popupShowFlag"
      mode="center"
      :round="10"
      @close="popupClose"
      @open="popupOpen"
    >
      <view class="honour-total-popup">
        <view class="title">
          <h3>{{ honourTotal }}</h3>
          <h5>项荣誉</h5>
        </view>
        <view class="honour-list">
          <view
            class="honour-item"
            v-for="(item, index) in honourTotalDataList"
            :key="index"
          >
            <view class="label">
              {{ item.label }}
            </view>
            <view class="value">
              <h4>
                {{ item.value }}
              </h4>
              <h5>项</h5>
            </view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup>
import { ref, onMounted, inject } from "vue";
import { onReachBottom } from "@dcloudio/uni-app";
import uniTag from "@/uni_modules/uni-tag/components/uni-tag/uni-tag.vue";
import uniDataChecklist from "@/uni_modules/uni-data-checkbox/components/uni-data-checkbox/uni-data-checkbox.vue";
import hederBox from "@/components/header/index.vue";
import EnterpriseItemCard from "./componts/enterprise-item-card.vue";
import { getTopSearch, getUserSearchHistoryList } from "../../api/index";
import { getUserInfoList, getCollectiveInfoList } from "@/api/honour/index.js";
import { getUserInfoPageListApi } from "@/api/honour/personal-list.js";
import { goodsPage } from "@/api/shopping/index.js";
import { getEnterpriseHonorCountSortMapApi } from "@/api/honour/enterprise-list";
import {
  getAppEnterpriseListApi,
  getEnterpriseHonorCountDetailsApi,
} from "@/api/honour/search";
import { customNav } from "@/utils/customNav";
import personalCard from "./componts/personal-card.vue";
const show = ref(true);
const changeName = ref("");
const changeVal = ref("");
const searchName = ref("");
const total = ref(0);
const isLoading = ref(false);
const localdata = ref([
  // {
  //   text: "政策",
  //   value: "政策",
  // },
  {
    text: "企业",
    value: "企业",
  },
  {
    text: "人才",
    value: "人才",
  },
  // {
  //   text: "集体",
  //   value: "集体",
  // },
  // {
  //   text: "商城",
  //   value: "商城",
  // },
]);
const listData = ref([]);
const HotData = ref([]);
const wxHuntStyle = ref({});
const historyData = ref([]);

function getTopSearchData() {
  getTopSearch().then((res) => {
    console.log("res", res);
    //    HotData.value = new Set(res.data);
    console.log(res.data);
    let arr = [];
    res.data.forEach((item) => {
      arr.push(item.filedName);
    });
    HotData.value = Array.from(new Set(arr));
    console.log(HotData.value);
  });

  if(uni.getStorageSync("token")) {
    getUserSearchHistoryList().then((res) => {
      historyData.value = res.data;
    });
  }
}

function tagClick(name) {
  show.value = false;
  searchName.value = name;
  changeName.value = "企业";
}

const hotTagClick = (name) => {
  show.value = false;
  isHotTag.value = true;
  searchName.value = name;
  changeName.value = "企业";
};

function changeChecklist(name) {
  console.log("选项卡", name);
  let newname = name.detail.value;
  changeVal.value = newname;
  curPage.value = 1;
  total.value = 0;
  listData.value = [];
  enterpriseList.value = [];
  switch (newname) {
    case "政策":
      listData.value = [
        {
          id: "1",
          title: "高新区出台了24个大数据企业扶持政策，快来看看有没有适合你的！",
          organization: "高新区管委会",
          time: "2024/1/20",
        },
      ];
      break;
    case "企业":
      getAppEnterpriseList();
      break;
    case "人才":
      getUserInfoListData();
      break;
    case "集体":
      getCollectiveInfoListData();
      break;
    case "商城":
      goodsPageData();
      break;

    default:
      break;
  }
}
function iconClick(name) {
  if (show.value) {
    show.value = false;
    changeName.value = "企业";
  }
  searchName.value = name;
  curPage.value = 1;
  listData.value = [];
  enterpriseList.value = [];
  switch (changeVal.value) {
    case "政策":
      listData.value = [
        {
          id: "1",
          title: "高新区出台了24个大数据企业扶持政策，快来看看有没有适合你的！",
          organization: "高新区管委会",
          time: "2024/1/20",
        },
      ];
      break;
    case "企业":
      getAppEnterpriseList();
      break;
    case "人才":
      getUserInfoListData();
      break;
    case "集体":
      getCollectiveInfoListData();
      break;
    case "商城":
      goodsPageData();
      break;

    default:
      break;
  }
}

function policyClick(item) {
  console.log(item);
}

const enterpriseList = ref([]);
const curPage = ref(1);
const curPageSize = ref(10);
const totalPages = ref(0);
const packageHonourPath = inject("packageHonourPath");

/**
 * 跳转企业详情页面
 * @param enterprise 当前点击企业
 */
const goEnterpriseDetail = (enterprise) => {
  console.log("详情", enterprise);
  console.log(packageHonourPath);
  // customNav(
  //   `${packageHonourPath}/enterprise-detail?name=${enterprise.enterpriseName}&typeName=企业&id=${enterprise.id}`
  // );
};
// 跳转个人详情
const personalDetails = (data) => {
  console.log(data);
  customNav(
    `/package_honour/pages/honour/enterprise-honor-personal?id=${data.id}`
  );
};
/**
 * 跳转到荣誉画像页面 当前点击企业
 * @param enterprise
 */
const goPortrayalPage = (enterprise) => {
  console.log("荣誉", enterprise);
  customNav(
    `${packageHonourPath}/enterprise-honor-detail?title=荣耀画像&name=${enterprise.enterpriseName}&id=${enterprise.id}`
  );
};
/* 弹出层部分start*/
const popupShowFlag = ref(false);
const popupOpen = () => {};
const popupClose = () => {
  popupShowFlag.value = false;
};
const honourTotalDataList = ref([]);
const honourTotal = ref(0);
const honorMap = ref({});
/**
 * 企业卡片荣誉总数按钮监听
 * @param enterpriseName 企业名称
 */
const handleHonourTotalClick = (enterpriseName) => {
  getHonorTotalSortKey(enterpriseName);
};

/**
 * 获取企业荣誉排序map
 * @param enterpriseName
 * @returns {Promise<void>}
 */
const getHonorTotalSortKey = async (enterpriseName) => {
  const res = await getEnterpriseHonorCountSortMapApi();
  const { code, data } = res;
  if (code === 200) {
    const validKeys = data;
    honorMap.value = data
      .filter((key) => validKeys.includes(key))
      .reduce((acc, key) => {
        acc[key] = "";
        return acc;
      }, {});
    await getHonorTotalData(enterpriseName);
  }
};

/**
 * 获取企业荣誉详情
 * @param enterpriseName 企业名称
 * @returns {Promise<void>}
 */
const getHonorTotalData = async (enterpriseName) => {
  const res = await getEnterpriseHonorCountDetailsApi({ enterpriseName });
  const { code, data } = res;
  if (code === 200) {
    honourTotal.value = data["总数"];
    const orderKeys = Object.keys(honorMap.value);
    const orderData = orderKeys.reduce((acc, key) => {
      acc[key] = data[key] || "0";
      return acc;
    }, {});
    honourTotalDataList.value = Object.keys(orderData)
      .map((key) => {
        if (key !== "总数") {
          return { label: key, value: data[key] };
        }
        return null;
      })
      .filter((item) => item !== null);
    popupShowFlag.value = true;
  }
};
/* 弹出层部分end */

/**
 * 获取企业列表
 * @returns {Promise<void>}
 */
const getAppEnterpriseList = async () => {
  const isHotParams = {
    enterpriseName: searchName.value,
  };
  const isNotHotParams = {
    enterpriseName: searchName.value,
  };
  const normalParams = {
    page: curPage.value,
    size: curPageSize.value,
  };
  const params = isHotTag.value
    ? Object.assign(isHotParams, normalParams)
    : Object.assign(isNotHotParams, normalParams);
  const res = await getAppEnterpriseListApi(params);
  const { code, data } = res;
  if (code === 200) {
    const { pages, records } = data || {};
    totalPages.value = pages;
    total.value = data.total;
    if (enterpriseList.value.length === 0) {
      enterpriseList.value = records;
    } else {
      enterpriseList.value = enterpriseList.value.concat(records);
    }
  }
};

onMounted(() => {
  getTopSearchData();
});
const isHotTag = ref(false);

// 人才数据接口
function getUserInfoListData() {
  isLoading.value = false;
  getUserInfoPageListApi({
    size: 10,
    page: curPage.value,
    realName: searchName.value,
  }).then((res) => {
    isLoading.value = true;
    console.log("getUserInfoPageListApi", res);

    total.value = res.data.total;
    enterpriseList.value = res.data.records;
  });
}
// 集体数据接口
function getCollectiveInfoListData() {
  isLoading.value = false;
  getCollectiveInfoList({
    size: 10,
    collectiveName: searchName.value,
    page: curPage.value,
    // collectiveTypeList: [searchName.value],
  }).then((res) => {
    isLoading.value = true;
    total.value = res.data.total;
    res.data.records.map((o) => {
      listData.value.push({
        title: o.collectiveName,
        list: o.collectiveHonorInfoList
          ? o.collectiveHonorInfoList.map((item) => {
              return item.collectiveHonor;
            })
          : [],
        imageUrl: o.avatar ? o.avatar : "",
        person: `法定代表人：${o.legalRepresentative} `,
        time: `成立于${o.establishTime} `,
        iconList: [
          {
            name: "荣耀画像",
            icon: "person",
          },
          {
            name: "企业空间",
            icon: "frends",
          },
        ],
      });
    });
  });
}
// 商城数据接口
function goodsPageData() {
  isLoading.value = false;
  goodsPage({
    size: 10,
    current: curPage.value,
    tsgName: searchName.value,
  }).then((res) => {
    console.log("goodsPageData", res);
    res.data.records.map((o) => {
      listData.value.push(o);
    });
    isLoading.value = true;
    total.value = res.data.total;
  });
}
onReachBottom((e) => {
  console.log(changeVal.value);
  console.log(total.value);
  
  // if (curPage.value <= totalPages.value) {
  //   curPage.value++;
  //   getAppEnterpriseList();
  // }
  if (total.value !== 0 || total.value >= 5) {
    uni.showLoading({
      title: "加载中...",
    });
    if (total.value <= curPage.value * 10) {
      setTimeout(() => {
        uni.showToast({
          icon: "none",
          title: "没有更多数据了",
        });
      }, 1000);
    } else {
      curPage.value++;
      switch (changeVal.value) {
        case "企业":
          getAppEnterpriseList();
          break;
        case "人才":
          getUserInfoListData();
          break;
        case "集体":
          getCollectiveInfoListData();
          break;
        case "商城":
          goodsPageData();
          break;

        default:
          break;
      }
      setTimeout(() => {
        uni.hideLoading();
      }, 300);
    }
  }
});
</script>


<style lang="less" scoped>
@import "@/static/style/global.less";

.content {
  min-height: 93vh;

  .hunt {
    position: relative;
    height: 80rpx;
    margin-bottom: 50rpx;
  }

  &.center {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .search-box {
    width: 95vw;
    margin: 0 auto;
    height: auto;

    .search-item {
      padding: 60rpx 0;
    }
  }

  .tabulation-box {
    width: 100vw;
    // background-color: #ffffff;
    padding-bottom: 50rpx;

    .tabulation-type {
      width: 90vw;
      padding: 0 5vw;
      position: sticky;
      position: -webkit-sticky;
      top: 80rpx;
      background: #ffffff;
      z-index: 100;
      display: flex;
      flex-flow: row nowrap;
      justify-content: center;
    }
  }
  .card-container {
    &:last-child {
      .enterprise-item-card {
        border-bottom: none;
      }
    }
    
  .btn-box-geren {
    display: flex;
    flex-flow: row nowrap;
    justify-content: flex-start;
    .btn {
      width: 150rpx;
      font-family: "ali";
      font-weight: 400;
      font-size: 23rpx;
      color: #9b9b9b;
      margin: 0 10rpx;
      margin-top: 20rpx;
      &:nth-child(1) {
        margin-left: 0;
      }
      &:after {
        border: 0;
      }
    }
  }
  }

  .honour-total-popup {
    width: 260rpx;
    padding: 19rpx 24rpx 35rpx 21rpx;
    box-shadow: 0 2rpx 13rpx 0 rgba(85, 144, 246, 0.5);
    border: 1px solid #5590f6;
    border-right: 7rpx;

    .title {
      display: flex;
      align-items: center;
      height: 30rpx;

      h3 {
        font-family: "DIN";
        font-weight: bold;
        font-size: 31rpx;
        color: #ff9c00;
      }

      h5 {
        font-family: "ali-m";
        font-weight: 400;
        font-size: 23rpx;
        color: #272636;
        margin-left: 8rpx;
      }
    }

    .honour-list {
      margin-top: 38rpx;

      .honour-item {
        display: flex;

        .label {
          flex: 1;
          font-family: "ali-m";
          font-weight: 400;
          font-size: 23rpx;
          color: #272636;
        }

        .value {
          display: flex;
          flex: 1;

          h4 {
            flex: 1;
            text-align: end;
            font-family: "DIN";
            font-weight: bold;
            font-size: 23rpx;
            color: #ff9c00;
          }

          h5 {
            flex: 1;
            text-align: start;
            font-family: "ali-m";
            font-weight: 400;
            font-size: 23rpx;
            color: #272636;
            margin-left: 12rpx;
          }
        }
      }
    }
  }
}
</style>
